import { Module, Global } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from './prisma.service';

/**
 * 数据库模块 - 零隐患MFIS规范
 * 解决隐患：#9 数据库事务处理，#10 重试策略
 */
@Global()
@Module({
  providers: [PrismaService],
  exports: [PrismaService],
})
export class DatabaseModule {
  constructor(private readonly prismaService: PrismaService, private readonly configService: ConfigService) {
    this.initializeDatabase();
  }

  private async initializeDatabase(): Promise<void> {
    try {
      // 测试数据库连接
      await this.prismaService.$connect();
      console.log('✅ 数据库连接成功');

      // 设置连接池参数
      const connectionLimit = this.configService.get<number>('DB_CONNECTION_LIMIT', 20);
      const connectionTimeout = this.configService.get<number>('DB_CONNECTION_TIMEOUT', 30000);

      console.log(`🔧 数据库配置: 连接池=${connectionLimit}, 超时=${connectionTimeout}ms`);

    } catch (error) {
      console.error('🚨 CRITICAL: 数据库连接失败', {
        error: error.message,
      });

      // 零容忍策略：数据库连接失败立即终止
      process.exit(1);
    }
  }
}